/**
 * Copyright 2018-2020 stylefeng & fengshuonan (https://gitee.com/stylefeng)
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.emove.modular.system.controller;

import cn.emove.config.properties.GunsProperties;
import cn.emove.core.common.annotion.BussinessLog;
import cn.emove.core.common.annotion.Permission;
import cn.emove.core.common.constant.Const;
import cn.emove.core.common.constant.dictmap.UserDict;
import cn.emove.core.common.constant.factory.ConstantFactory;
import cn.emove.core.common.constant.state.TicketStatus;
import cn.emove.core.common.exception.BizExceptionEnum;
import cn.emove.core.common.page.LayuiPageFactory;
import cn.emove.core.log.LogObjectHolder;
import cn.emove.core.shiro.ShiroKit;
import cn.emove.core.shiro.ShiroUser;
import cn.emove.core.util.HttpUtil;
import cn.emove.modular.system.entity.TicketEntity;
import cn.emove.modular.system.entity.User;
import cn.emove.modular.system.model.OrderDispatchDto;
import cn.emove.modular.system.model.OrderDto;
import cn.emove.modular.system.model.TicketModel;
import cn.emove.modular.system.service.DictService;
import cn.emove.modular.system.service.TicketService;
import cn.emove.modular.system.service.UserService;
import cn.emove.modular.system.warpper.TicketWrapper;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import cn.stylefeng.roses.kernel.model.exception.ServiceException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 系统管理员控制器
 *
 * @author fengshuonan
 * @Date 2017年1月11日 下午1:08:17
 */
@Controller
@RequestMapping("/ticket")
public class TicketController extends BaseController {
    private final static Logger logger = LoggerFactory.getLogger(TicketController.class);

    private static String PREFIX = "/modular/system/ticket/";

    @Autowired
    private GunsProperties gunsProperties;

    @Autowired
    private TicketService ticketService;

    @Autowired
    private UserService userService;
    @Autowired
    private DictService dictService;
    @Autowired
    private HttpServletRequest request;

    /**
     * 跳转到查看管理员列表的页面
     *
     * @author jiaojiaxiang
     * @Date 2019/04/18 10:50
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "ticket.html";
    }
    @RequestMapping("/list")
    @Permission
    @ResponseBody
    public Object list(@RequestParam(required = false) String orderNo,
                       @RequestParam(required = false) String shopName,
                       @RequestParam(required = false) String shopAdr,
                       @RequestParam(required = false) String createTime,
                       @RequestParam(required = false) String type,
                       @RequestParam(required = false) String describes,
                       @RequestParam(required = false) String repairType) {

        //拼接查询条件
        String beginTime = "";
        String endTime = "";
        String contactName = "";

        if (ToolUtil.isNotEmpty(createTime)) {
            String[] split = createTime.split(" - ");
            beginTime = split[0];
            endTime = split[1];
        }
        int orderSource = 1;
        Page<Map<String, Object>> tickets = ticketService.selectTickets(null, orderNo, orderSource, beginTime, endTime, contactName,shopName,shopAdr,type,null,describes, repairType);
        Page wrapped = new TicketWrapper(tickets).wrap();
        return LayuiPageFactory.createPageInfo(wrapped);

    }

    /**
     * 跳转至派单页面
     * @return
     */
    @Permission
    @RequestMapping(value = "/ticket_dispatch")
    public String ticketDispatch(@RequestParam int orderId,String typeName,Model model) {
        if (ToolUtil.isEmpty(orderId)) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        model.addAttribute("orderId", orderId);
        model.addAttribute("typeName", typeName);
        System.out.println("打开分配页面");
        return PREFIX + "ticket_dispatch.html";
    }

    /**
     * 查询派单的用户下拉框
     * @return
     */
    @RequestMapping("/userData")
    @ResponseBody
    public JSONObject selectServer(){
        System.out.println("获取用户下拉框");
        List<Map<String,Object>> userList = new ArrayList<Map<String,Object>>();
        userList = userService.selectStaffUser();
        JSONObject ServerJson = new JSONObject();
        for (Map<String,Object> c : userList) {
            ServerJson.put(String.valueOf(c.get("userId")), c.get("name"));
        }
        return ServerJson;
    }

    @RequestMapping(value = "/dispatchSave")
    @BussinessLog(value = "派单", key = "userId", dict = UserDict.class)
    @Permission(Const.ADMIN_NAME)
    @ResponseBody
    public ResponseData dispatchSave(OrderDispatchDto dispatchDto) {
        String ip = dictService.selectByCode("service_intranet_ip").get(0).getDescription();
        String url = ip+"/api/backstage/orderAllocation?orderId="+dispatchDto.getOrderId()+"&userId="+dispatchDto.getUserId()+"&allocationContent="+dispatchDto.getContent();
        logger.info(url);
        String result = HttpUtil.sendGet(url);
        logger.info(result);
        if(result!=""){
            JSONObject json = JSONObject.parseObject(result);
            String code = String.valueOf(json.get("code"));
            if("200".equals(code)){
                return SUCCESS_TIP;
            }else{
                throw new ServiceException(BizExceptionEnum.SERVER_ERROR);
            }
        }else {
            throw new ServiceException(BizExceptionEnum.SESSION_TIMEOUT);
        }

    }
    /**
     * 跳转到添加工单
     *
     * @author jiaojiaxiang
     *      * @Date 2019/04/18 10:50
     **/
    @RequestMapping(value = "/add")
    public String roleAdd() {
        return PREFIX + "ticket_add.html";
    }

    /**
     * 查询商户下拉框
     * @return
     */
    @RequestMapping("/shopData")
    @ResponseBody
    public JSONObject selectShopData(){
        List<Map<String,Object>> userList = new ArrayList<Map<String,Object>>();
        userList = userService.selectShopData();
        JSONObject ServerJson = new JSONObject();
        for (Map<String,Object> c : userList) {
            ServerJson.put(String.valueOf(c.get("shopId")), c.get("shopName"));
        }
        return ServerJson;
    }

    @RequestMapping(value = "/addSave")
    @BussinessLog(value = "保存", key = "shopId", dict = UserDict.class)
    @Permission(Const.ADMIN_NAME)
    @ResponseBody
    public ResponseData addSave(OrderDto orderDto) {
        ShiroUser shiroUser = ShiroKit.getUserNotNull();
        String userId = shiroUser.getId();
        orderDto.setCreateUser(userId);
        String ip = dictService.selectByCode("service_intranet_ip").get(0).getDescription();
        String url = ip+"/api/backstage/backstageOrderSave";
        String param = JSON.toJSONString(orderDto);
        String result = HttpUtil.post(url,param);
        System.out.println(result);
        if(result!=""){
            JSONObject json = JSONObject.parseObject(result);
            String code = String.valueOf(json.get("code"));
            if("200".equals(code)){
                return SUCCESS_TIP;
            }else{
                throw new ServiceException(BizExceptionEnum.SERVER_ERROR);
            }
        }else {
            throw new ServiceException(BizExceptionEnum.SESSION_TIMEOUT);
        }

    }

    /**
     * 跳转至详情页面
     * @return
     */
    @Permission
    @RequestMapping(value = "/ticket_detail")
    public String ticketDetail(@RequestParam int orderId,String typeName,Model model) {
        if (ToolUtil.isEmpty(orderId)) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        model.addAttribute("orderId", orderId);
        model.addAttribute("typeName", typeName);
        LogObjectHolder.me().set(orderId);
        return PREFIX + "ticket_detail.html";
    }

    /**
     * 查询派单的用户下拉框
     * @return
     */
    @RequestMapping("/ticketDetailData/{orderId}")
    @Permission(Const.ADMIN_NAME)
    @ResponseBody
    public Object ticketDetailData(@PathVariable int orderId) {
        String  u = request.getHeader("Referer");
        u = u.replace("localhost","140.206.191.44");
        u = u.replace("192.168.1.42","140.206.191.44");
        System.out.println(u);
        logger.info("当前路径："+u);
        String ip = dictService.selectByCode("service_intranet_ip").get(0).getDescription();
        String url = ip+"/api/backstage/orderDetail?orderId="+orderId+"&url="+u;
        String result = HttpUtil.sendGet(url);
        System.out.println(result);
        if(result!=""){
            JSONObject json = JSONObject.parseObject(result);
            JSONObject data = JSONObject.parseObject(json.get("data").toString());
            String logStr = data.get("repairSchedule").toString();
            JSONArray logList = JSONArray.parseArray(logStr);
            List<JSONObject> logs = new ArrayList<>();
            for(Object object : logList){
                JSONObject o = (JSONObject) object;
                User user = userService.selectAPPUserById(o.get("operatorId").toString());
                if (user==null) {
                    user=userService.selectUserById(o.get("operatorId").toString());
                }
                String createUserName = "";
                if (ToolUtil.isNotEmpty(user) && ToolUtil.isNotEmpty(user.getName())) {
                    createUserName =  user.getName();
                }
                o.put("createUserName",createUserName);
                String desc = o.get("staffOperationDesc").toString();
                if(desc.contains("派单中")){
                    o.put("status","待派单");
                }else if(desc.contains("报修工单已创建")){
                    o.put("status","待派单");
                }else if(desc.contains("维修中")){
                    o.put("status","维修中");
                }else if(desc.contains("无法处理")){
                    o.put("status","无法处理");
                }else if(desc.contains("已完成")){
                    o.put("status","已完成");
                }else if(desc.contains("已作废")){
                    o.put("status","已作废");
                }else if(desc.contains("已转单")){
                    o.put("status","已转单");
                }else if(desc.contains("已处理")){
                    o.put("status","已完成");
                }else if(desc.contains("处理人")){
                    o.put("status","维修中");
                }
                String roleId = user.getRoleId();
                String[] roles = roleId.split(",");
                if(isHave(roles,"2")){
                    o.put("role","商户");
                }else if(isHave(roles,"3")){
                    o.put("role","员工");
                }else{
                    o.put("role","平台");
                }
                logs.add(o);
            }
            String operatorId = data.get("operatorId").toString();
            json.put("operatorName",ConstantFactory.me().getOperatorName(operatorId));
            data.put("repairSchedule",logs);
            json.put("data",data);
            String code = String.valueOf(json.get("code"));
            if("200".equals(code)){
                return json;
            }else{
                throw new ServiceException(BizExceptionEnum.SERVER_ERROR);
            }
        }else {
            throw new ServiceException(BizExceptionEnum.SESSION_TIMEOUT);
        }
    }
    public static boolean isHave(String[] strs,String s){

        /*此方法有两个参数，第一个是要查找的字符串数组，第二个是要查找的字符或字符串*/
        int i = strs.length;
        while (i-- > 0){
            if(s.equals(strs[i])){
                return true;
            }
        }
        return false;
    }
    /**
     * 审核
     */
    @RequestMapping(value = "/audit")
    @ResponseBody
    public ResponseData audit(@RequestParam Integer flag,Integer orderId,String remark) {
        String ip = dictService.selectByCode("service_intranet_ip").get(0).getDescription();
        String url = ip+"/api/backstage/backstageUpdateOrder";
        ShiroUser shiroUser = ShiroKit.getUserNotNull();
        String userId = shiroUser.getId();
        JSONObject jsonData = new JSONObject();
        jsonData.put("id",orderId);
        jsonData.put("createUser",userId);
        jsonData.put("remark",remark);
        if(flag==1){
            //审核通过
            jsonData.put("type",13);
        }else if(flag==0){
            //审核拒绝
            jsonData.put("type",15);
        }
        String param = JSON.toJSONString(jsonData);
        String result = HttpUtil.post(url,param);
        System.out.println(result);
        if(result!=""){
            JSONObject json = JSONObject.parseObject(result);
            String code = String.valueOf(json.get("code"));
            if("200".equals(code)){
                return SUCCESS_TIP;
            }else{
                throw new ServiceException(BizExceptionEnum.SERVER_ERROR);
            }
        }else {
            throw new ServiceException(BizExceptionEnum.SESSION_TIMEOUT);
        }

    }

    /**
     * 跳转至审核页面
     * @return
     */
    @Permission
    @RequestMapping(value = "/ticket_audit")
    public String ticketAudit(@RequestParam int orderId,Model model) {
        if (ToolUtil.isEmpty(orderId)) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        model.addAttribute("orderId", orderId);
        LogObjectHolder.me().set(orderId);
        return PREFIX + "ticket_audit.html";
    }
    //导出
    @RequestMapping("/exportData")
    @ResponseBody
    public Object getList() {

       /* model.addAttribute("WEB_URL", ServiceUrl.WEB_URL);
        model.addAttribute("WEB_NAME", ServiceUrl.WEB_NAME);*/



        Map<String, Object> map = new HashMap<String, Object>();

        try {
            //List<TicketEntity> mList = ticketService.selectAllTicket();
            List<TicketEntity> mList = new ArrayList<TicketEntity>();
            if (mList.size() > 0) {
                //查询所有数据
                /*for (TicketEntity ticketEntity : mList) {
                    //自定义一个新实体类，定义好要导出来的字段，把遍历出来的数据存放到一个新的list，因为会出现关联表的数据
                    SellDealExcelEntity sellDeal = new SellDealExcelEntity();
                    sellDeal.setSdId(sellDealEntity.getSdId());
                    sellDeal.setShopName(sellDealEntity.getSellEntity().getShopName());
                    sellDeal.setSdTime(sellDealEntity.getSdTime());
                    //时间格式可能不对，备用
//                DateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//                String time = format.format(sellDealEntity.getSdTime());
                    //根据类型 set 对应的值
                    switchType(sellDealEntity,sellDeal);
                    sellDeal.setSdWater(sellDealEntity.getSdWater());
                    //判断如果订单是null，就set " - "
                    if (sellDealEntity.getOrderFormEntity()==null){
                        sellDeal.setOrder("-");
                    }else {
                        sellDeal.setOrder(sellDealEntity.getOrderFormEntity().getOfOrder());
                    }
                    list.add(sellDeal);
                }*/
            }

            map.put("code", 0);
            map.put("msg", "导出成功");
            map.put("count", mList.size());
            map.put("data", mList);
        }catch (Exception e){
            map.put("code", 1);
            map.put("msg", "导出失败，请稍后重试！");
        }


        return JSON.toJSON(map);
    }

        /**
         * 导出报表
         * @return
         */
        @RequestMapping(value = "/export")
        @ResponseBody
        public List<TicketModel> export(@RequestParam(required = false) int orderSource,
                                        @RequestParam(required = false) String orderNo,
                                        @RequestParam(required = false) String contactName,
                                        @RequestParam(required = false) String shopName,
                                        @RequestParam(required = false) String shopAdr,
                                        @RequestParam(required = false) String createTime,
                                        @RequestParam(required = false) String type,
                                        @RequestParam(required = false) String describes,
                                        @RequestParam(required = false) String repairType) throws Exception {

            //拼接查询条件
            String beginTime = "";
            String endTime = "";

            if (ToolUtil.isNotEmpty(createTime)) {
                String[] split = createTime.split(" - ");
                beginTime = split[0];
                endTime = split[1];
            }
            //Page<Map<String, Object>> tickets = ticketService.selectTickets(null, orderNo, orderSource, beginTime, endTime, contactName,shopName,shopAdr,type,null);
            //获取数据
            List<TicketModel> list = ticketService.selectAllTicket(orderSource,orderNo,beginTime,endTime,contactName,shopName,shopAdr,type,describes,repairType);
            List<TicketModel> mList = new ArrayList<>();
            for (TicketModel data : list) {
                //自定义一个新实体类，定义好要导出来的字段，把遍历出来的数据存放到一个新的list，因为会出现关联表的数据
                TicketModel sellDeal = new TicketModel();
                sellDeal.setOrderNo(data.getOrderNo()+"\t");
                sellDeal.setShopName(data.getShopName());
                sellDeal.setShopAdr(data.getShopAdr());
                sellDeal.setCreateTime(String.valueOf(data.getCreateTime()));
                sellDeal.setTypeName(TicketStatus.getDescription(data.getType()));
                sellDeal.setContactName(data.getContactName());
                sellDeal.setDescribes(data.getDescribes()+"\t");
                sellDeal.setOperatorName(ConstantFactory.me().getOperatorName(data.getOperatorId()));
                sellDeal.setRepairType(data.getRepairType());
                if(data.getUpdateTime()!=null){
                    sellDeal.setUpdateTime(data.getUpdateTime());
                }
                if(data.getContactPhone()!=null&&!"".equals(data.getContactPhone())){
                    sellDeal.setContactPhone(data.getContactPhone().replaceAll("(\\d{3})\\d{4}(\\d{4})","$1****$2"));
                }

                mList.add(sellDeal);
            }
            return mList;
    }
    /**
     * 跳转至作废页面
     * @return
     */
    @Permission
    @RequestMapping(value = "/cancel")
    public String cancel(@RequestParam int orderId,Model model) {
        if (ToolUtil.isEmpty(orderId)) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        model.addAttribute("orderId", orderId);
        LogObjectHolder.me().set(orderId);
        return PREFIX + "ticket_cancel.html";
    }
    /**
     * 作废保存
     */
    @RequestMapping(value = "/cancelSave")
    @ResponseBody
    public ResponseData cancelSave(@RequestParam Integer orderId,String cancelContent) {
        String ip = dictService.selectByCode("service_intranet_ip").get(0).getDescription();
        String url = ip+"/api/backstage/backstageUpdateOrder";
        ShiroUser shiroUser = ShiroKit.getUserNotNull();
        String userId = shiroUser.getId();
        JSONObject jsonData = new JSONObject();
        jsonData.put("id",orderId);
        jsonData.put("createUser",userId);
        jsonData.put("cancelContent",cancelContent);
        jsonData.put("type",16);
        String param = JSON.toJSONString(jsonData);
        String result = HttpUtil.post(url,param);
        System.out.println(result);
        if(result!=""){
            JSONObject json = JSONObject.parseObject(result);
            String code = String.valueOf(json.get("code"));
            if("200".equals(code)){
                return SUCCESS_TIP;
            }else{
                throw new ServiceException(BizExceptionEnum.SERVER_ERROR);
            }
        }else {
            throw new ServiceException(BizExceptionEnum.SESSION_TIMEOUT);
        }

    }
    @RequestMapping("/getNotice")
    @ResponseBody
    public Object getNotice() {
        JSONObject json = new JSONObject();
        List list= new ArrayList();

        List<TicketModel> tickets = ticketService.selectNewTickets();
        boolean hpPos = ShiroKit.hasPermission("/ticket/ticket_dispatch");
        boolean hpStaff = ShiroKit.hasPermission("/staffTicket/ticket_dispatch");
        for(TicketModel t:tickets){

            if(hpPos&&hpStaff){
                String s = "";
                if(t.getOrderSource()==1){
                    s = "商户";
                }else if(t.getOrderSource()==2){
                    s = "员工";
                }
                Map map = new HashMap();
                map.put("orderId",t.getId());
                map.put("orderNo",t.getOrderNo());
                map.put("orderSource",t.getOrderSource());
                map.put("content","有个新建的"+s+"工单");
                list.add(map);
            }else if(hpPos&&!hpStaff){
                if(t.getOrderSource()==1){
                    String s = "商户";
                    Map map = new HashMap();
                    map.put("orderId",t.getId());
                    map.put("orderNo",t.getOrderNo());
                    map.put("orderSource",t.getOrderSource());
                    map.put("content","有个新建的"+s+"工单");
                    list.add(map);
                }
            }else if(!hpPos&&hpStaff){
                if(t.getOrderSource()==2){
                    String s = "员工";
                    Map map = new HashMap();
                    map.put("orderId",t.getId());
                    map.put("orderNo",t.getOrderNo());
                    map.put("orderSource",t.getOrderSource());
                    map.put("content","有个新建的"+s+"工单");
                    list.add(map);
                }
            }
        }

        json.put("noticeList",list);
        json.put("noticeCount",list.size());
        return json;
    }

}